<?php

namespace app\common\library;
use app\common\constant\Common;

class MobileMsg 
{

    
    public function sendMessage($msg,$username)
    {
		//return 1;//关闭发送消息
		
	    //科技处
		/*
	   $appid="636FCD3A-0F62-5584-2B9B-C1DEB1F800B6";
		$appsecret="3F3BEE14-4976-44FD-B355-97E8826195F5";
		 $userid='00000500214';*/
      
       //合作发规处
	   $appid="47E96708-A892-FBE1-375D-BC84A0D78BAB";
       $appsecret="C6CC6018-670E-CBA0-0A9D-8FE80E6AE1B8";
	   $userid='00000500217';	
	   $url="http://49.234.36.16:8080/api/send";
		 
		 //步骤1：获取token
		 
		$token=$this->getToken($appid,$appsecret);	
		
     //$this->write_log('url地址：'.$url);
     
	 //步骤2：封装参数
		$message = [
		"fromuser"=>$userid,			
		 "content"=>$msg,
		  "type"=>"text",
		  "priority"=>"1",
		'tools' => [[ 'tool' => 'mobile' ],[ 'tool' => 'daiban' ]], 
		'tousers' => [['touser' => $username]],
		];
	
		$msg= json_encode($message, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);


      	$post_data = array(
			"appid"=>$appid,
			"tokenid"=>$token,
			"schoolcode"=>1,
            "message"=>$msg
  
        ); 
		
		$this->write_log('post数据：'.json_encode($post_data));
		
		//步骤3：发送请求
		$ch = curl_init();
		curl_setopt_array($ch, array(
			CURLOPT_URL            => $url,
			CURLOPT_RETURNTRANSFER => 1,
			 CURLOPT_HEADER=>0,			
			 CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $post_data
		));
	
		$res = curl_exec($ch);	
        curl_close($ch);
	
	
	   $this->write_log('返回数据：'.$res);
       
	   $res=json_decode($res);
       return $res->retmsg;	
	

    
}

public function getToken($appid,$appsecret)
{   
	
	$url='http://49.234.36.16:8080/api/token';
	$post_data = array(
        "appid"         => $appid,
        "appsecret"     => $appsecret,
		"schoolcode"=>1

    ); 
	
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL            => $url,
		
        CURLOPT_RETURNTRANSFER => 1,
		 CURLOPT_HEADER=>0,
		 CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $post_data,
    ));
    $output = curl_exec($ch);
	
    curl_close($ch);
	
    $output=json_decode($output);
	//$this->write_log($output);
	$this->write_log($output->access_token);
    return $output->access_token;

}

	public function write_log($data){ 
   
    //设置路径目录信息
    $url = '/log/'.date('Ymd').'_log.txt';  
    $dir_name=dirname($url);
      //目录不存在就创建
      if(!file_exists($dir_name))
      {
        //iconv防止中文名乱码
       $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
      }
      $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建       
    fwrite($fp,date("Y-m-d H:i:s").var_export($data,true)."\r\n");//写入文件
    fclose($fp);//关闭资源通道
}
 




}